﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Threading;
using System.Globalization;
using System.IO;
using System.Text;
using System.Net;
using System.Xml;
using System.Linq;

using CE.Image;
using CE.User;
using CE.Company;
using CE.Global;

public partial class home : MyLanguageBasePage
{
  
    protected void Page_Load(object sender, EventArgs e)
    {
        //if (Request.Browser.IsMobileDevice == true || (Request.Browser.ScreenPixelsWidth <= 640 && Request.Browser.ScreenPixelsHeight <= 960))
        //{
            //string mobileurl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.MobileURL");
            //Response.Redirect(mobileurl);
        //}

        if (isMobileBrowser())
        {
            string mobileurl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.MobileURL");
            Response.Redirect(mobileurl);
        }

        Master.Page.Title = Resources.Title.HomeTitle;

        LiteralControl newln = new LiteralControl(Environment.NewLine);
        HtmlMeta language = new HtmlMeta();
        language.Name = "language";
        language.Content = Resources.Title.PageLanguage;

        HtmlMeta keywords = new HtmlMeta();
        keywords.Name = "keywords";
        keywords.Content = Resources.Title.HomeKeyword;

        HtmlMeta description = new HtmlMeta();
        description.Name = "description";
        description.Content = Resources.Title.HomeDescription;

        Page.Header.Controls.AddAt(10, new LiteralControl(Environment.NewLine));
        Page.Header.Controls.AddAt(11, language);
        Page.Header.Controls.AddAt(12, new LiteralControl(Environment.NewLine));
        Page.Header.Controls.AddAt(13, keywords);
        Page.Header.Controls.AddAt(14, new LiteralControl(Environment.NewLine));
        Page.Header.Controls.AddAt(15, description);
        divhotline.Style.Add("background-image", "url('"+Resources.ImageResource.CallUsNow+"')");
        if (!IsPostBack)
        {

            Session[CE.Global.General.OrderRefNo] = null; //Sakthi on 10 Jan 2012
            //divSubscribe.Visible = true;
            //divThankYou.Visible = false;
            //txtEmail.Text = "";

            hplChartis.NavigateUrl = CE.Global.General.GetUrl("/partners/chartis-insurance.aspx", Page);
            hplAZCP.NavigateUrl = CE.Global.General.GetUrl("/partners/azcp-insurance.aspx", Page);
            hplAXA.NavigateUrl = CE.Global.General.GetUrl("/partners/axa-insurance.aspx", Page);
            hplBKI.NavigateUrl = CE.Global.General.GetUrl("/partners/bki-insurance.aspx", Page);
            hplDhipaya.NavigateUrl = CE.Global.General.GetUrl("/partners/dhipaya-insurance.aspx", Page);
            hplKrungthai.NavigateUrl = CE.Global.General.GetUrl("/partners/krungthai-insurance.aspx", Page);
            hplKSK.NavigateUrl = CE.Global.General.GetUrl("/partners/ksk-insurance.aspx", Page);
            hplLMG.NavigateUrl = CE.Global.General.GetUrl("/partners/lmg-insurance.aspx", Page);
            hplMittare.NavigateUrl = CE.Global.General.GetUrl("/partners/mittare-insurance.aspx", Page);
            hplMSIG.NavigateUrl = CE.Global.General.GetUrl("/partners/msig-insurance.aspx", Page);
            hplMTI.NavigateUrl = CE.Global.General.GetUrl("/partners/muangthai-insurance.aspx", Page);
            hplSCSMG.NavigateUrl = CE.Global.General.GetUrl("/partners/scsmg-insurance.aspx", Page);
            hplSMK.NavigateUrl = CE.Global.General.GetUrl("/partners/synmunkong-insurance.aspx", Page);
            hplThaivivat.NavigateUrl = CE.Global.General.GetUrl("/partners/thaivivat-insurance.aspx", Page);
            hplTMS.NavigateUrl = CE.Global.General.GetUrl("/partners/tokio-insurance.aspx", Page);
            hplViriyah.NavigateUrl = CE.Global.General.GetUrl("/partners/viriyah-insurance.aspx", Page);

            linkC1single.NavigateUrl = CE.Global.General.GetUrl("/car-insurance/car-details.aspx", Page);
            hplHowToBuy.NavigateUrl = CE.Global.General.GetUrl("/faq/howtopurchase.aspx", Page);
            hplReminder.NavigateUrl = CE.Global.General.GetUrl("/car-insurance/set-insurance-reminder.aspx", Page);
            hplGetQuote.NavigateUrl = CE.Global.General.GetUrl("/car-insurance/car-details.aspx", Page);

            linkCarInsurance.HRef = CE.Global.General.GetUrl("/car-insurance/car-details.aspx", Page);
            aTest.HRef = CE.Global.General.GetUrl("/car-insurance/ggquick.aspx", Page);
            if (Request.Params["lang"] != null)
            {
                if (Request.Params["lang"].ToString() != "th-TH")
                {
                    litZopim.Visible = true;
                }
                else
                {
                    litZopim.Visible = false;
                }
            }
            
            //alinkTerm.HRef = CE.Global.General.GetUrl("/terms/luckydraw.aspx", Page);

            //GETS RSS FEEDS FROM GLUAYGLUAY.BIZ
            string lang = "th";
            if (language.Content != null)
                lang = language.Content.ToString();
            GetRSS(lang);
        }


        //if (Session["Language"] == "th-TH")
        //{
        //    divcallme.Visible = false;
        //    divhotline.Visible = true;
        //}
        //else
        //{
        //    divcallme.Visible = true;
        //    divhotline.Visible = false;
        //}
    }

    public static bool isMobileBrowser()
    {
        //GETS THE CURRENT USER CONTEXT
        HttpContext context = HttpContext.Current;

        //FIRST TRY BUILT IN ASP.NT CHECK
        if (context.Request.Browser.IsMobileDevice)
        {
            return true;
        }
        //THEN TRY CHECKING FOR THE HTTP_X_WAP_PROFILE HEADER
        if (context.Request.ServerVariables["HTTP_X_WAP_PROFILE"] != null)
        {
            return true;
        }
        //THEN TRY CHECKING THAT HTTP_ACCEPT EXISTS AND CONTAINS WAP
        if (context.Request.ServerVariables["HTTP_ACCEPT"] != null &&
            context.Request.ServerVariables["HTTP_ACCEPT"].ToLower().Contains("wap"))
        {
            return true;
        }
        //AND FINALLY CHECK THE HTTP_USER_AGENT 
        //HEADER VARIABLE FOR ANY ONE OF THE FOLLOWING
        if (context.Request.ServerVariables["HTTP_USER_AGENT"] != null)
        {
            //Create a list of all mobile types
            string[] mobiles =
                new[]
                {
                    "midp", "j2me", "avant", "docomo", 
                    "novarra", "palmos", "palmsource", 
                    "240x320", "opwv", "chtml",
                    "pda", "windows ce", "mmp/", 
                    "blackberry", "mib/", "symbian", 
                    "wireless", "nokia", "hand", "mobi",
                    "phone", "cdm", "up.b", "audio", 
                    "SIE-", "SEC-", "samsung", "HTC", 
                    "mot-", "mitsu", "sagem", "sony"
                    , "alcatel", "lg", "eric", "vx", 
                    "NEC", "philips", "mmm", "xx", 
                    "panasonic", "sharp", "wap", "sch",
                    "rover", "pocket", "benq", "java", 
                    "pt", "pg", "vox", "amoi", 
                    "bird", "compal", "kg", "voda",
                    "sany", "kdd", "dbt", "sendo", 
                    "sgh", "gradi", "jb", "dddi", 
                    "moto", "iphone"
                };

            //Loop through each item in the list created above 
            //and check if the header contains that text
            foreach (string s in mobiles)
            {
                if (context.Request.ServerVariables["HTTP_USER_AGENT"].ToLower().Contains(s.ToLower()))
                {
                    return true;
                }
            }
        }

        return false;
    }

    /*
    protected void ibtSubscribe_Click(object sender, EventArgs e)
    {
        ChangeValidationEffectServerSide("subscriber");
        if (Page.IsValid)
        {
            UserSubscriber _usersub = new UserSubscriber();
            UserSubscriberDB _usersubdb = new UserSubscriberDB();
            _usersub.Email = txtEmail.Text;
            if (_usersubdb.AlreadyExist(_usersub.Email) > 0)
            {
                divSubscribe.Visible = false;
                divThankYou.Visible = true;
                lblThankYou.Text = "";
                lblThankYou.Visible = false;
                lblExist.Visible = true;
                //lblExist.Text = "Your email is already existing in our list!";
            }
            else if (_usersubdb.Insert(_usersub) > 0)
            {
                divSubscribe.Visible = false;
                divThankYou.Visible = true;
                lblExist.Text = "";
                lblThankYou.Visible = true;
                lblExist.Visible = false;
                //lblThankYou.Text = "Your email has been added in E-Newsletter list. Thank you very much!";
            }
        }
    }

    private void ChangeValidationEffectServerSide(string strValidationGroup)
    {
        //Email
        if (rfvEmail.Enabled && rfvEmail.ValidationGroup == strValidationGroup)
        {
            rfvEmail.Validate();
            if (rfvEmail.IsValid == false)
            {
                txtEmail.ControlStyle.CssClass = "validationError";
            }
            else
            {
                txtEmail.ControlStyle.CssClass = "";
            }
        }
        else
        {
            txtEmail.ControlStyle.CssClass = "";
        }

        if (revEmail.Enabled && revEmail.ValidationGroup == strValidationGroup)
        {
            if (rfvEmail.IsValid)
            {
                revEmail.Validate();
                if (revEmail.IsValid == false)
                {
                    txtEmail.ControlStyle.CssClass = "validationError";
                }
                else
                {
                    txtEmail.ControlStyle.CssClass = "";
                }
            }
        }
        else
        {
            txtEmail.ControlStyle.CssClass = "";
        }
    }
    */

    private void GetRSS(string lang)
    {
        string _feedurl = "http://www.gluaygluay.biz/wp/?feed=rss2&lang=";
        string _lang = "th";
        if (lang == "thai")
        {
            _lang = "th";
            lblResourceCentre.Text = "แหล่งข้อมูล";
        }
        else if (lang == "english")
        {
            _lang = "en";
            lblResourceCentre.Text = "Resource Centre";
        }

        aGGbiz.HRef = "http://www.gluaygluay.biz/wp/?lang=" + _lang;


        try
        {
            //Create a WebRequest
            WebRequest rssReq =
            WebRequest.Create(_feedurl + _lang);
            //Get the WebResponse
            WebResponse rep = rssReq.GetResponse();

            using (var reader = new System.IO.StreamReader(rep.GetResponseStream()))
            {
                var feedContents = reader.ReadToEnd();

                var document = System.Xml.Linq.XDocument.Parse(feedContents);

                var posts = (from p in document.Descendants("item")
                             select new
                             {
                                 Title = p.Element("title").Value,
                                 Link = p.Element("link").Value,
                                 Comments = p.Element("comments").Value,
                                 PubDate = DateTime.ParseExact(p.Element("pubDate").Value, "ddd, dd MMM yyyy HH:mm:ss zzz", CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces),
                                 Description = p.Element("description").Value
                             }).ToList();

                var dataSet = new DataSet();
                var blog = new DataTable("Blog");
                blog.Columns.Add("Title", typeof(string));
                blog.Columns.Add("Link", typeof(string));
                blog.Columns.Add("Comments", typeof(string));
                blog.Columns.Add("PubDate", typeof(string));
                blog.Columns.Add("Description", typeof(string));
                dataSet.Tables.Add(blog);

                foreach (var post in posts)
                {
                    var newRow = blog.NewRow();
                    newRow["Title"] = post.Title;
                    newRow["Link"] = post.Link;
                    newRow["Comments"] = post.Comments;
                    newRow["PubDate"] = post.PubDate;
                    newRow["Description"] = post.Description;

                    blog.Rows.Add(newRow);
                }

                rssRepeater.DataSource = dataSet;
                rssRepeater.DataBind();
            }
        }
        catch (Exception ex)
        {
        }
    }
}
